package com.revenant.driver.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nanchen.compresshelper.CompressHelper;
import com.revenant.driver.R;
import com.revenant.driver.adapter.AddNewDriverInfoAdaper;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.Driver.ColorAndEnergerBean;
import com.revenant.driver.bean.Driver.SearchEmptyBean;
import com.revenant.driver.bean.InviteCode;
import com.revenant.driver.bean.NewCarEditBean;
import com.revenant.driver.bean.NewDriverAddInfo;
import com.revenant.driver.bean.ShipperBean.FileUploadBean;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.SPUtils;
import com.revenant.driver.utils.Utils;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.revenant.driver.utils.Constants.AddCarAndTrailer;
import static com.revenant.driver.utils.Constants.AddCarAndTrailerNewUpdate;
import static com.revenant.driver.utils.Constants.CallNumber;
import static com.revenant.driver.utils.Constants.Driver_Car_Color;
import static com.revenant.driver.utils.Constants.Name_header_token;
import static com.revenant.driver.utils.Constants.SelectInvite;
import static com.revenant.driver.utils.Constants.SelectOneCar;
import static com.revenant.driver.utils.Constants.SelectOneCarNew;
import static com.revenant.driver.utils.Constants.UploadFile;

public class CarManageEditActivity extends BaseActivity {

    private String cartypeid = "-1";
    @BindView(R.id.new_left)
    ImageView newLeft;
    @BindView(R.id.new_center)
    TextView newCenter;
    @BindView(R.id.new_right)
    ImageView newRight;
    @BindView(R.id.new_show_title)
    LinearLayout newShowTitle;
    @BindView(R.id.new_recyclerview)
    RecyclerView newRecyclerview;
    @BindView(R.id.select_one)
    NiceSpinner selectOne;
    @BindView(R.id.select_two)
    NiceSpinner selectTwo;
    @BindView(R.id.new_recyclerviewtwo)
    RecyclerView newRecyclerviewtwo;
    @BindView(R.id.select_three)
    NiceSpinner selectThree;
    @BindView(R.id.new_btn_format)
    Button newBtnFormat;
    private List<String> listNameOne = Arrays.asList(
            "行驶证正本",
            "行驶证副本",
            "营运证"
    );
    private List<Integer> listImageOne = Arrays.asList(

            R.mipmap.xingshizhengforeground,
            R.mipmap.xingshizhengback,
            R.mipmap.congyezigezhneg
    );
    private List<String> listNameTwo = Arrays.asList(
            "挂车行驶证正本",
            "挂车行驶证副本",
            "挂车营运证"
    );
    private List<Integer> listImageTwo = Arrays.asList(
            R.mipmap.xingshizhengforeground,
            R.mipmap.xingshizhengback,
            R.mipmap.congyezigezhneg
    );
    private AddNewDriverInfoAdaper adaperone;
    private AddNewDriverInfoAdaper adapertwo;
    private List<LocalMedia> selectList = new ArrayList<>();
    private Context context;
    private List<NewDriverAddInfo> listusersone = new ArrayList<>();
    private List<NewDriverAddInfo> listuserstwo = new ArrayList<>();
    private int selectindex = -1;
    private int selecttype = -1;
    private String Name_header;

    List<String> color = new ArrayList<>();
    List<String> colorCode = new ArrayList<>();
    List<String> energe = new ArrayList<>();
    List<String> energeCode = new ArrayList<>();
    List<String> colorTwo = new ArrayList<>();
    List<String> colorCodeTwo = new ArrayList<>();
    private int isImages = -1;
    private String spinnera = "";
    private String spinnerb = "";
    private String spinnerc = "";

    @Override
    public int getContentViewResId() {
        context = this;
        return R.layout.activity_add_new_vertival;
    }

    @Override
    public void initView() {
        Name_header = Utils.get64String() + "_" + SPUtils.getUserPhone(context) + "_" + "1";
        cartypeid = getIntent().getStringExtra("cartypeid");

        adaperone = new AddNewDriverInfoAdaper();
        newRecyclerview.setLayoutManager(new GridLayoutManager(context, 2));
        newRecyclerview.setAdapter(adaperone);

        adapertwo = new AddNewDriverInfoAdaper();
        newRecyclerviewtwo.setLayoutManager(new GridLayoutManager(context, 2));
        newRecyclerviewtwo.setAdapter(adapertwo);

        newCenter.setText("编辑车辆");
        newBtnFormat.setText("提交审核");
    }

    @Override
    protected boolean isshowtitlebar() {
        return false;
    }

    @Override
    public void initData() {
        color.add("请选择");
        colorCode.add("-1");

        energe.add("请选择");
        energeCode.add("-1");

        colorTwo.add("请选择");
        colorCodeTwo.add("-1");

        for (int i = 0; i < listNameOne.size(); i++) {
            NewDriverAddInfo user = new NewDriverAddInfo();
            user.setImage(listImageOne.get(i));
            user.setTitle(listNameOne.get(i));
            user.setImageUrl("");
            listusersone.add(user);
        }
        adaperone.addData(listusersone);

        adaperone.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                selecttype = 1;
                selectindex = position;
                showBottomSheetDialog(CarManageEditActivity.this);
            }
        });


        for (int i = 0; i < listNameTwo.size(); i++) {
            NewDriverAddInfo user = new NewDriverAddInfo();
            user.setImage(listImageTwo.get(i));
            user.setTitle(listNameTwo.get(i));
            user.setImageUrl("");
            listuserstwo.add(user);
        }
        adapertwo.addData(listuserstwo);
        selectonecar(cartypeid);
        adapertwo.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                selecttype = 2;
                selectindex = position;
                showBottomSheetDialog(CarManageEditActivity.this);
            }
        });


        selectOne.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (position == 0) {
                    spinnera = "";
                } else {
                    spinnera = colorCode.get(position);

                }
            }
        });

        selectTwo.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (position == 0) {
                    spinnerb = "";
                } else {
                    spinnerb = energeCode.get(position);

                }
            }
        });

        selectThree.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                if (position == 0) {
                    spinnerc = "";
                } else {
                    spinnerc = colorCodeTwo.get(position);

                }
            }
        });



    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.new_left, R.id.new_right, R.id.new_btn_format})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.new_left:
                finish();
                break;
            case R.id.new_right:
                /**/
                selectPhone(CarManageEditActivity.this);
//                Utils.callPhone(CarManageEditActivity.this, CallNumber);
                break;
            case R.id.new_btn_format:
                isImages = -1;
                for (int i = 0; i < listNameOne.size(); i++) {
                    if (adaperone.getData().get(i).getImageUrl().isEmpty()) {
                        showToast("请输入" + listNameOne.get(i));
                        isImages = 0;
                        break;
                    }
                }
                if (isImages != 0 && selectOne.getSelectedIndex() < 1) {
                    showToast("请输入" + "车牌颜色");
                } else if (isImages != 0 && selectTwo.getSelectedIndex() < 1) {
                    showToast("请输入" + "车辆能源");
                } else if (selectOne.getSelectedIndex() > 0 && selectTwo.getSelectedIndex() > 0 && isImages != 0) {
                    String photoa = adaperone.getData().get(0).getImageUrl();
                    String photob = adaperone.getData().get(1).getImageUrl();
                    String photoc = adaperone.getData().get(2).getImageUrl();

                    String photod = adapertwo.getData().get(0).getImageUrl();
                    String photoe = adapertwo.getData().get(1).getImageUrl();
                    String photof = adapertwo.getData().get(2).getImageUrl();
                    if (!(photod.isEmpty() ^ photoe.isEmpty() ^ photof.isEmpty() ^ spinnerc.isEmpty())) {
                        showDig();
                        updateGoodsDetail(cartypeid,
                                spinnera,
                                spinnerb,
                                photoa,
                                photob,
                                photoc,
                                photod,
                                photoe,
                                photof,
                                spinnerc
                        );
                    } else {
                        showToast("补全挂车信息");
                    }


                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        if (!selectList.isEmpty()) {
                            showDig();
//                            uploadAvatar(media.getPath());
                            String url = media.getPath().startsWith("content://") ? media.getAndroidQToPath() : media.getPath();
                            uploadAvatar(url, selectindex);
                        }
                    }
                    break;
            }
        }
    }

    private void uploadAvatar(final String path, int select) {
        File file = new File(path);
        File newfile = CompressHelper.getDefault(context).compressToFile(file);

        OkGo.<String>post(UploadFile)
                .tag(this)
                .isMultipart(true)

                .params("file", newfile)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        if (response.code() == 200) {
                            FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                            if (fileUploadBean.getCode().equals("0")) {
                                if (selecttype == 1) {
                                    adaperone.getData().get(select).setImageUrl(fileUploadBean.getData().getUrl());
                                    adaperone.getData().get(select).setSelecttype(0);
                                    adaperone.notifyItemChanged(select);
                                } else if (selecttype == 2) {
                                    adapertwo.getData().get(select).setImageUrl(fileUploadBean.getData().getUrl());
                                    adapertwo.getData().get(select).setSelecttype(0);
                                    adapertwo.notifyItemChanged(select);
                                }


                            } else {
                                showToast(fileUploadBean.getMsg());
                            }
                        } else {
                            showToast(response.message());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        dismissDig();
                        super.onError(response);
                        showToast(response.message());
                    }
                });
    }

    private void updateGoodsDetail(
            String id,
            String vehiclePlateColorCode,
            String vehicleEnergyType,
            String drivingLicenseImgJust,
            String drivingLicenseImgBack,
            String operationCertificate,
            String trailerLicenseImgJust,
            String trailerLicenseImgBack,
            String trailerOperationCertificate,
            String trailerVehiclePlateColorCode
    ) {
        OkGo.<String>post(AddCarAndTrailerNewUpdate)
                .headers(Name_header_token, Name_header)
                .params("id", id)
                .params("carDriverId", id)
                .params("vehiclePlateColorCode", vehiclePlateColorCode)
                .params("vehicleEnergyType", vehicleEnergyType)
                .params("drivingLicenseImgJust", drivingLicenseImgJust)
                .params("drivingLicenseImgBack", drivingLicenseImgBack)
                .params("operationCertificate", operationCertificate)
                .params("accountId", SPUtils.getAccounId(context))
                .params("trailerLicenseImgJust", trailerLicenseImgJust)
                .params("trailerLicenseImgBack", trailerLicenseImgBack)
                .params("trailerOperationCertificate", trailerOperationCertificate)
                .params("trailerVehiclePlateColorCode", trailerVehiclePlateColorCode)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.d("testAAAAAA"+response.body());
                        dismissDig();
                        if (!response.body().isEmpty()){
                            SearchEmptyBean g = GsonUtil.parseJsonWithGson(response.body(), SearchEmptyBean.class);
                            if (g!=null){
                                if (g.getCode()!=null){
                                    if (g.getCode().equals("0")) {
                                        showToast(g.getMsg());
                                        finish();
                                        startActivity(DriverVehicleManageActivity.class);
                                    } else {
                                        showToast(g.getMsg());
                                    }
                                }
                            }
                        }






                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.d("testAAAAAA"+response.body());
                        dismissDig();
                    }
                });
    }

    private void getColor() {

        OkGo.<String>get(Driver_Car_Color)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        ColorAndEnergerBean colorAndEnergerBean = GsonUtil.parseJsonWithGson(response.body(), ColorAndEnergerBean.class);
                        if (colorAndEnergerBean.getCode().equals("0")) {
                            if (colorAndEnergerBean.getData().getColList() != null && colorAndEnergerBean.getData().getColList().size() > 0) {
                                for (int i = 0; i < colorAndEnergerBean.getData().getColList().size(); i++) {
                                    color.add(colorAndEnergerBean.getData().getColList().get(i).getName());
                                    colorCode.add(colorAndEnergerBean.getData().getColList().get(i).getCode());
                                    energe.add(colorAndEnergerBean.getData().getEnList().get(i).getName());
                                    energeCode.add(colorAndEnergerBean.getData().getEnList().get(i).getCode());
                                    colorTwo.add(colorAndEnergerBean.getData().getColList().get(i).getName());
                                    colorCodeTwo.add(colorAndEnergerBean.getData().getColList().get(i).getCode());
                                }
                                selectOne.attachDataSource(color);
                                selectTwo.attachDataSource(energe);
                                selectThree.attachDataSource(color);
                                for (int i = 0; i < colorCode.size(); i++) {
                                    if (colorCode.get(i).equals(spinnera)){
                                        selectOne.setSelectedIndex(i);
                                    }
                                }

                                for (int i = 0; i < energeCode.size(); i++) {
                                    if (energeCode.get(i).equals(spinnerb)){
                                        selectTwo.setSelectedIndex(i);
                                    }
                                }

                                for (int i = 0; i < colorCodeTwo.size(); i++) {
                                    if (colorCodeTwo.get(i).equals(spinnerc)){
                                        selectThree.setSelectedIndex(i);
                                    }
                                }




                            }

                        }else {
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void selectonecar(String id) {
        showDig();
        OkGo.<String>get(SelectOneCarNew)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code() == 200) {

                            NewCarEditBean bean = GsonUtil.parseJsonWithGson(response.body(), NewCarEditBean.class);
                            if (bean.getCode().contains("0")) {
                                dismissDig();
                                getColor();
                                spinnera = bean.getData().getVehiclePlateColorCode();
                                spinnerb = bean.getData().getVehicleEnergyType();
                                adaperone.getData().get(0).setImageUrl(bean.getData().getDrivingLicenseImgJust());
                                adaperone.getData().get(0).setSelecttype(0);
                                adaperone.getData().get(1).setImageUrl(bean.getData().getDrivingLicenseImgBack());
                                adaperone.getData().get(1).setSelecttype(0);
                                adaperone.getData().get(2).setImageUrl(bean.getData().getOperationCertificate());
                                adaperone.getData().get(2).setSelecttype(0);
                                adaperone.notifyDataSetChanged();



                                if (bean.getData().getTrailerLicenseImgJust()!=null&&!bean.getData().getTrailerLicenseImgJust().trim().isEmpty()){
                                    spinnerc=bean.getData().getTrailerVehiclePlateColorCode();
                                    adapertwo.getData().get(0).setImageUrl(bean.getData().getTrailerLicenseImgJust());
                                    adapertwo.getData().get(0).setSelecttype(0);
                                    adapertwo.getData().get(1).setImageUrl(bean.getData().getTrailerLicenseImgBack());
                                    adapertwo.getData().get(1).setSelecttype(0);
                                    adapertwo.getData().get(2).setImageUrl(bean.getData().getTrailerOperationCertificate());
                                    adapertwo.getData().get(2).setSelecttype(0);
                                    adapertwo.notifyDataSetChanged();

                                }

                            } else {
                                showToast(bean.getMsg());
                                dismissDig();
                            }

                        }else {
                            dismissDig();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast(response.message());
                        dismissDig();
                    }
                });
    }
}